package com.zhongwang.business.module.taskManage.controller;

import com.zhongwang.business.base.BaseController;
import com.zhongwang.business.common.JsonResult;
import com.zhongwang.business.module.basic.service.BusinessGroupService;
import com.zhongwang.business.module.system.log.LogService;
import com.zhongwang.business.module.system.util.XYHFileUtils;
import com.zhongwang.business.module.taskManage.dao.UnassignedTaskDao;
import com.zhongwang.business.module.taskManage.model.*;
import com.zhongwang.business.module.taskManage.service.*;
import org.apache.poi.util.Internal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Integer.parseInt;

@Controller
public class TaskBaseInfoController extends BaseController {
    @Autowired
    private TaskBaseInfoService taskBaseInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskDistributeService taskDistributeService;
    @Autowired
    private UnassignedTaskService unassignedTaskService;
    @Autowired
    private TaskFormRelationService taskFormRelationService;
    @Autowired
    private BusinessGroupService businessGroupService;
    @Autowired
    private LogService logService;
    @Autowired
    private UnassignedTaskDao unassignedTaskDao;
    JsonResult jsonResult=new JsonResult();
    /**
     * 点击申请，执行添加或者修改
     * @param model
     * @return
     */
    @PostMapping("/taskBase/insert")
    @ResponseBody
    //@RequiresPermissions({"drive:toolsb:add"})
    public JsonResult insert(TaskBaseInfoModel model){
        JsonResult jsonResult = new JsonResult();
        Integer flg=taskBaseInfoService.insertTaskBaseInfo(model);
        if(flg==1){
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("创建成功");
        }
        else{
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("创建失败");
        }
        return jsonResult;
    }

    /**
     * 删除销售项目
     * @param id
     * @return
     */
    @PostMapping("/taskBase/del")
    @ResponseBody
    //@RequiresPermissions({"drive:toolsb:add"})
    public JsonResult del(Integer id,Integer fkid ){
        JsonResult jsonResult = new JsonResult();
        Integer flg=taskBaseInfoService.delTaskBaseInfo(id,fkid);
        if(flg==1){
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("删除成功");
        }
        else{
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("删除失败");
        }
        return jsonResult;
    }
    /**
     * 查询已经下达项目列表
     * @param fkId
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/taskList")
    public JsonResult selectTaskList(Integer fkId) {
        startPage();
        return jsonResult(taskService.selTaskList(fkId));
    }
    /**
     * 查询已经下达项目列表
     * @param fkId
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/updTaskList")
    public JsonResult updTaskList(Integer fkId,String param,Integer costId,Integer contractId,String remark) {
        JsonResult jsonResult=new JsonResult();
        try {
                TaskModel task = new TaskModel();
                //外键：商务信息id
                task.setFkId(fkId);
                // 1#预算#需要1#1&2|2#报价#不需要0#|
                String[] sourceStrArray = param.split("\\:");
                for (int i2 = 0; i2 < sourceStrArray.length; i2++) {
                    String[] sourceStrArray3 = sourceStrArray[i2].split("\\#");
                    if (sourceStrArray3.length >= 3) {
                        //根据fkid和kind 直接修改需要不需要。
                        //然后将id返回，根据id删除以前的关系，插入新的对应组关系。
                        task.setTkind(parseInt(sourceStrArray3[0]));
                        task.setIsNeed(parseInt(sourceStrArray3[2]));
                        if (sourceStrArray3.length >4) {
                            task.setAppoint(sourceStrArray3[4]);
                        }else{
                            task.setAppoint("");
                        }
//                        if(task.getTkind()==1 || task.getTkind()==6 || task.getTkind()==7){
//                            //预核算成本组id
//                            task.setGroupId(costId);
//                        }else{
//                            //合同组id
//                            task.setGroupId(contractId);
//                        }
                        //代表是需要
                        int flgUpd = taskService.updateTask(task);
                        int id=taskService.selTaskId(task);
                    }

                }
            /**
             * 修改备注
             */
            UnassignedTaskModel untask=new UnassignedTaskModel();
                untask.setId(fkId);
                untask.setRemark(remark);
                unassignedTaskService.updUnassignedReamrk(untask);

                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("调整成功");

        }catch (Exception e){
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("调整失败:"+e.getMessage());
        }
        //循环选择的项目组和商务任务，执行保存
        return jsonResult;
    }

    /**
     * 待下达列表页面
     * @return
     */
    @GetMapping("/taskBoard")
    public String linkTaskBoardRelease(Model model) {
//        isPoint
        List<UnassignedTaskModel> list=unassignedTaskService.selectYears();
        model.addAttribute("yearList",list);
        return "/taskManage/board/mainBoard";
    }
    /**
     * 查询看板项目列表
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/allTaskList")
    public JsonResult selectAllTaskList(UnassignedTaskModel model) {
        startPage();
        return jsonResult(unassignedTaskService.selectAllProjectTaskList(model));
    }

    /**
     * 根据下达项目的主键id，查找任务的进程。
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectTaskProgressById")
    public JsonResult selectTaskProgressById(Integer id){
        return jsonResult(unassignedTaskService.selectTaskProgressById(id));
    }

    /**
     * 采集数据的进程
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectDataStatusById")
    public JsonResult selectDataStatusById(Integer id, Integer kind)
    {
//        startPage();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setKind(kind);
        //tkind 7概算 1预算 6核算
        //-任务类别：1是预算，2是核算，3是概算
        //概算
        if(kind ==7)
        {
            model.setTaskType(3);
        }
        //预算
        else if(kind ==1)
        {
            model.setTaskType(1);
        }
        //核算
        else if(kind ==6)
        {
            model.setTaskType(2);
        }

        return jsonResult(unassignedTaskService.selectDataStatusById(model));
    }


    /**
     * 任务审批的进程
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectAppProgressById")
    public JsonResult selectAppProgressById(Integer id,Integer taskid)
    {
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setTaskid(taskid);
        return jsonResult(unassignedTaskService.selectAppProgressById(model));
    }
    /**
     * 任务审批的进程
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectNodeFilesById")
    public JsonResult selectNodeFilesById(Integer id,String fileKind)
    {
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setFileTypes(fileKind);
        return jsonResult(unassignedTaskService.selectNodeFilesById(model));
    }
    /**
     * 任务审批的进程
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectContractFilesById")
    public JsonResult selectContractFilesById(Integer id,String fileKind)
    {
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setFileTypes(fileKind);
        List<TaskBoardModel> taskBoardModelList = unassignedTaskDao.selectContractFilesById(model);
        return jsonResult(taskBoardModelList);
    }

    /**
     * 任务节点附件的数量
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectFilescCntById")
    public JsonResult selectFilescCntById(Integer id,Integer taskid)
    {
        JsonResult jsonResult=new JsonResult();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setTaskid(taskid);
        return jsonResult.setData(unassignedTaskService.selectFilescCntById(model));
    }

    /**
     * 任务节点-报价附件的数量
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectBJFilescCntById")
    public JsonResult selectBJFilescCntById(Integer id)
    {
        JsonResult jsonResult=new JsonResult();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        return jsonResult.setData(unassignedTaskService.selectBJFilescCntById(model));
    }

    /**
     * 任务节点-hetong附件的数量
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectHTFilescCntById")
    public JsonResult selectHTFilescCntById(Integer id)
    {
        JsonResult jsonResult=new JsonResult();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        int count = unassignedTaskService.selectHTFilescCntById(model);
        return jsonResult.setData(count);
    }

    /**
     * 任务节点-kuanpiao附件的数量
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectKPFilescCntById")
    public JsonResult selectKPFilescCntById(Integer id)
    {
        JsonResult jsonResult=new JsonResult();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        return jsonResult.setData(unassignedTaskService.selectKPFilescCntById(model));
    }

    /**
     * 看板的详细页面
     * @return
     */
    @GetMapping("/taskDetailBoard")
    public String linkDetailBoard(UnassignedTaskModel modelPar,Model model) {
//        model.addAttribute("id",modelPar.getId());
//        model.addAttribute("code",modelPar.getCode());

//        model.addAttribute("name",modelPar.getName());
//        model.addAttribute("num",modelPar.getNum());
//        model.addAttribute("demander",modelPar.getDemander());
//        model.addAttribute("address",modelPar.getAddress());
        /**
         * 地址栏传参数不靠谱，用code进行查询。
         */
        UnassignedTaskModel projectBaseInfo=unassignedTaskService.selectTaskOfProjectByCode(modelPar.getCode());
        projectBaseInfo.setId(modelPar.getId());
        model.addAttribute("projectBaseInfo",projectBaseInfo);
        UnassignedTaskModel mm=unassignedTaskService.selectUnTaskOfRemark(modelPar.getId());
        if(mm!=null){
            model.addAttribute("remark",mm.getRemark());
        }else{
            model.addAttribute("remark","");
        }
        /**
         * 查找到所有的组的信息
         */
//        List<BusinessGroupModel> gourpList=businessGroupService.selectAllGroupList();
//        List<TaskModel> taskList=taskService.selTaskList(modelPar.getId());
////        model.addAttribute("gourpList",gourpList);
////        model.addAttribute("taskList",taskList);
//
//        List<TaskModel> tableData= new ArrayList<>();
//        /**
//         * 固定的列头
//         */
//        TaskModel taskTemp=new TaskModel();
//        taskTemp.setGroupName("工作组");
//        taskTemp.setYs("预算");
//        taskTemp.setBj("报价");
//        taskTemp.setHt("合同");
//        taskTemp.setFp("发票");
//        taskTemp.setHk("回款");
//        taskTemp.setHs("核算");
//
//        tableData.add(taskTemp);
//        /**
//         * 表格内部数据
//         */
//        for (int i=0;i<gourpList.size();i++){
//            TaskModel taskTemp0=new TaskModel();
//            taskTemp0.setGroupId(gourpList.get(i).getId());
//            taskTemp0.setGroupName(gourpList.get(i).getGroupName());
//            for(int j=0;j<taskList.size();j++){
//                switch(taskList.get(j).getTkind()) {
//                    case 1:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setYs("");
//                        }else{
//                            //需要
//                            taskTemp0.setYs(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                    case 2:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setBj("");
//                        }else{
//                            //需要
//                            taskTemp0.setBj(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                    case 3:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setHt("");
//                        }else{
//                            //需要
//                            taskTemp0.setHt(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                    case 4:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setFp("");
//                        }else{
//                            //需要
//                            taskTemp0.setFp(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                    case 5:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setHk("");
//                        }else{
//                            //需要
//                            taskTemp0.setHk(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                    case 6:
//                        if(taskList.get(j).getIsNeed().equals(0)){
//                            taskTemp0.setHs("");
//                        }else{
//                            //需要
//                            taskTemp0.setHs(taskList.get(j).getTstatus().toString());
//                        }
//                        break;
//                }
//                tableData.add(taskTemp0);
//            }
//        }

        model.addAttribute("tableData",taskService.selTaskIsUse(modelPar.getId()));

        model.addAttribute("gaisuan",taskService.getAppointByIdAndKind(modelPar.getId(),7));
        model.addAttribute("yusuan",taskService.getAppointByIdAndKind(modelPar.getId(),1));
        model.addAttribute("baojia",taskService.getAppointByIdAndKind(modelPar.getId(),2));
        model.addAttribute("hetong",taskService.getAppointByIdAndKind(modelPar.getId(),3));
        model.addAttribute("kuanpiao",taskService.getAppointByIdAndKind(modelPar.getId(),4));
        model.addAttribute("hesuan",taskService.getAppointByIdAndKind(modelPar.getId(),6));
        return "/taskManage/board/detailInfo";
    }



    /**
     * 看板的详细页面
     * @return
     */
    @GetMapping("/detail")
    public String linkDetailInfo(Integer id, Model model) {

        /*这部分显示页面上的checkBox列表的值*/
        model.addAttribute("taskInfo", unassignedTaskService.selectOneTaskInfo(id));
        model.addAttribute("groupList", taskService.selTaskList(id));
        return "/taskManage/board/detail";
    }

    @ResponseBody
    @PostMapping("/task/linkDetail")
    public JsonResult  linkDetail(Integer id,Integer tkind){
        JsonResult jsonResult=new JsonResult();
        Integer bll_id=unassignedTaskService.linkDetail(id, tkind);
        if(bll_id>0){
            jsonResult.setData(bll_id);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
        }else{
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("暂时无法查看呦！");
        }
        return  jsonResult;
    }

    /**
     * 任务的备注
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/taskBase/selectReamrkById")
    public JsonResult selectReamrkById(Integer id, Integer kind)
    {
//        startPage();
        TaskBoardModel model=new TaskBoardModel();
        model.setId(id);
        model.setKind(kind);

        JsonResult jsonResult=new JsonResult();
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        TaskBoardModel m=unassignedTaskService.selectReamrkById(model);
        String remark="";
        if(m!=null){
            remark=m.getRemark();
        }
        jsonResult.setData(remark);
        return jsonResult;
    }
    /**
     * 下载单个文件
     *
     * @param fileId
     * @param fileType
     * @param response
     * @throws Exception
     */
    @GetMapping("/downloadFile/{fileId}/{fileType}")
    public void downloadFile(
            @PathVariable("fileId") Integer fileId,
            @PathVariable("fileType") Integer fileType,
            HttpServletResponse response)
            throws Exception {
        File file = null;

//         fileListModel = null;
//        fileListModel.setId(fileId);
        TaskBoardModel fileListModel = unassignedTaskService.selectFilesById(fileId);
        file = new File("e:\\business\\upload\\" + fileListModel.getDataSource().substring(7).replace("/", "\\"));
        String fileTypeStr="";
        fileType=fileListModel.getTkind();
        if(fileType==29) {
            fileTypeStr = "概算附件";
        }
        else if(fileType==30){
            fileTypeStr= "预算附件";
        }
        else if(fileType==35)
        {
            fileTypeStr = "核算单附件";
        }else{
            fileTypeStr=  "";
        }

        logService.saveLog("单项目看板","下载了,"+fileTypeStr+"：《"+fileListModel.getDataName()+"》。");
        XYHFileUtils.download(file, fileListModel.getDataName(), response);
    }
    /**
     * 文件打包下载
     *
     * @param param
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/downloadPackage")
    public void downloadPackage(TaskBoardModel param, HttpServletResponse response) throws Exception {
        String[] fileIdArray = param.getDataName().split(",");
        List<TaskBoardModel> requestList = new ArrayList<>();
        List files = new ArrayList();
        String logContent = "";
        for (int i = 0; i < fileIdArray.length; i++) {
            File file = null;

            TaskBoardModel fileListModel = null;

            fileListModel = unassignedTaskService.selectFilesById(Integer.valueOf(fileIdArray[i]));

            file = new File("e:\\business\\upload\\" + fileListModel.getDataSource().substring(7).replace("/", "\\"));
            String fileTypeStr="";
            Integer fileType=fileListModel.getTkind();
            if(fileType==29) {
                fileTypeStr = "概算附件";
            }
            else if(fileType==30){
                fileTypeStr= "预算附件";
            }
            else if(fileType==35)
            {
                fileTypeStr = "核算单附件";
            }else{
                fileTypeStr=  "";
            }
            logContent+=fileTypeStr+"：《"+fileListModel.getDataName()+"》，";

            files.add(file);
        }
        logContent = logContent.substring(0,logContent.length()-1);
        if (files.size() > 0) {
            XYHFileUtils.downLoadFiles(files, response);
            logService.saveLog("单项目看板","打包下载了,"+logContent+"。");
        }
    }
}
